package com.zhiyou.crud.controller;

import com.zhiyou.crud.bean.*;
import com.zhiyou.crud.service.ProjectPublishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


//项目发布相关的controller
@Controller
public class ProjectControl {

    @Autowired
    ProjectPublishService pps;

    @RequestMapping("/gotoProjectInfo")
    public String gotoProjectInfo(HttpSession session){

        User u= (User)session.getAttribute("user");
        if(u==null){
            return "login";
        }

        if(u.getRealstatus()!=3){
            return "user";
        }


        List<Type> allTypes = pps.getAllTypes();
        session.setAttribute("projectTypesList",allTypes);

        User user = (User)session.getAttribute("user");
        //根据uno获得草稿项目  如果有的话保存到session中  (一个用户只能保存一个草稿)
        Project projectTemp = pps.getProjectTemp(user.getUno());
//        Project projectTemp = pps.getProjectTemp(99);
        System.out.println(projectTemp);
        session.setAttribute("projectTemp",projectTemp);

        //如果草稿项目不为空,查询对应的回报信息
        List<Back> backList = new ArrayList<>();
        if(projectTemp!=null){
           backList = pps.getBacksByPno(projectTemp.getPno());
        }
        session.setAttribute("backList",backList);




        return "/new_info";
    }



    //保存"项目信息"的草稿
    @RequestMapping("/tempProjectInfo")
    public String fileUpload(MultipartFile file,Project project, String province,String city, HttpServletRequest request) throws IOException {
        User u= (User)request.getSession().getAttribute("user");
        if(u==null){
            return "login";
        }
        if(u.getRealstatus()!=3){
            return "user";
        }

        // 先获取到文件要保存的路径


        String realPath = request.getRealPath("/images/static");


        System.out.println("【绝对路径】" + realPath);

        String newFileName = null;
        if(((Project)request.getSession().getAttribute("projectTemp"))!=null){
            newFileName=((Project)request.getSession().getAttribute("projectTemp")).getUrlpicture();
        }

        System.out.println(newFileName);


        try{
            System.out.println(file.isEmpty());
            if((!file.isEmpty())&&newFileName==null){
                // 获取文件后缀名，然后为文件起一个新名字（使用 UUID 避免重名）
                System.out.println("【原文件名】" + file.getOriginalFilename());
                String fileName = file.getOriginalFilename();
                String suffix = fileName.substring(fileName.lastIndexOf("."));
                newFileName = UUID.randomUUID().toString() + suffix;
                System.out.println("【新文件名】" + newFileName);
            }
        }catch (Exception e){

        }

        String urlpicture= newFileName;

        if(newFileName!=null){
            // 新建一个文件对象
            File target = new File(realPath, newFileName);

            // 如果存放路径不存在，就新建一个
            if (!target.getParentFile().exists()) {
                // 新建文件夹
                if (!target.getParentFile().mkdirs()) {
                    System.out.println("【目录为空】新建文件夹失败！");
                    return null;
                }
            }
            try {
                // 成功的话将文件保存
                file.transferTo(target);
            }catch (Exception e){

            }

        }

        Project project1=(Project) request.getSession().getAttribute("projectTemp");
         String psite=province+city;
         if(psite.contains("选择")||province==null){
             psite="河南省郑州市";
         }
        if(project1!=null){
            //如果项目不为null  则只需要更新
            System.out.println("project1 = " + project1);
            project1.setPtitle(project.getPtitle());
            project1.setPstory(project.getPstory());

//        System.out.println(psite);
            project1.setPsite(psite);
            project1.setUrlpicture(urlpicture);
            project1.setPtarget(project.getPtarget());
            project1.setPdays(project.getPdays());
            project1.setPlable(project.getPlable());
            project1.setTno(project.getTno());
            //根据uno更新临时项目  并重新设置  projectTemp 的session值
            pps.updateTempProject(project1);
        }else {
            project.setUrlpicture(urlpicture);
            project.setPsite(psite);
            User user=(User)request.getSession().getAttribute("user");
            project.setUno(user.getUno());
            project.setPstatus(0);
//            System.out.println("project = " + project);
            int i = pps.addProject(project);
            if(i>0){
                project1= pps.getProjectTemp(user.getUno());
            }

        }



        request.getSession().setAttribute("projectTemp",project1);

        System.out.println(project1.getUrlpicture()+"kkkkkk");

        return "new_info";
    }






    //保存“详细描述”的草稿
    @RequestMapping("/tempSaveDetail")
    public String tempSaveDetail(MultipartFile file,Project project,HttpServletRequest request) throws IOException {
        //首先判断登录及实名状态

        //如果未登录
        User u= (User)request.getSession().getAttribute("user");
        if(u==null){
            return "login";
        }

        //如果已登录但未实名
        if(u.getRealstatus()!=3){
            return "user";
        }

        // 先获取到文件要保存的路径

        String realPath = request.getRealPath("/images/static");
//        String realPath = "D:\\IdeaProjects\\spring-s3\\src\\main\\webapp\\static";
        System.out.println("【绝对路径】" + realPath);

        Project project1=(Project)request.getSession().getAttribute("projectTemp");

        String newFileName= null;

        if(project1!=null){
            newFileName=project1.getUrlvideo();
        }

        System.out.println(newFileName);

        try{
            System.out.println(file.isEmpty());
            if((!file.isEmpty())&&(newFileName==null||newFileName.trim()=="")){
                // 获取文件后缀名，然后为文件起一个新名字（使用 UUID 避免重名）
                System.out.println("【原文件名】" + file.getOriginalFilename());
                String fileName = file.getOriginalFilename();
                String suffix = fileName.substring(fileName.lastIndexOf("."));
                newFileName = UUID.randomUUID().toString() + suffix;
                System.out.println("【新文件名】" + newFileName);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        String urlvideo= newFileName;

        if(newFileName!=null){
            // 新建一个文件对象
            File target = new File(realPath, newFileName);

            // 如果存放路径不存在，就新建一个
            if (!target.getParentFile().exists()) {
                // 新建文件夹
                if (!target.getParentFile().mkdirs()) {
                    System.out.println("【目录为空】新建文件夹失败！");
                    return null;
                }
            }
            try {
                // 成功的话将文件保存
                file.transferTo(target);
            }catch (Exception e){

            }

        }



        if(project1!=null){
            project1.setUrlvideo(urlvideo);
            project1.setPother(project.getPother());

            //根据uno更新临时项目  并重新设置  projectTemp 的session值
            pps.updateTempProject(project1);
        }else {
            project.setUrlvideo(urlvideo);
            project.setPother(project.getPother());
            User user=(User)request.getSession().getAttribute("user");
            project.setUno(user.getUno());
            project.setPstatus(0);
            pps.addProject(project);
            project1= pps.getProjectTemp(user.getUno());
        }



        request.getSession().setAttribute("projectTemp",project1);

        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "new_detail";
    }


    //无论从哪个页面点击  "详细描述"  都要先跳到此 controller
    @RequestMapping("/gotoNewDetail")
    public String gotoNewDetail(HttpSession session){
        //首先判断登录及实名状态

        //如果未登录
        User user = (User)session.getAttribute("user");
        if(user==null){
            return "login";
        }

        //如果已登录但未实名
        if(user.getRealstatus()!=3){
            return "user";
        }

        return "new_detail";
    }

    //无论从哪个页面点击  "项目信息"  都要先跳到此 controller
    @RequestMapping("/gotoNewInfo")
    public String gotoNewInfo(HttpSession session){
        //首先判断登录及实名状态

        //如果未登录
        User user = (User)session.getAttribute("user");
        if(user==null){
            return "login";
        }

        //如果已登录但未实名
        if(user.getRealstatus()!=3){
            return "user";
        }

        return "new_info";
    }

    //无论从哪个页面点击  "回报设置"  都要先跳到此 controller
    @RequestMapping("/gotoNewBack")
    public String gotoNewBack(HttpSession session){
        //首先判断登录及实名状态

        //如果未登录
        User user = (User)session.getAttribute("user");
        if(user==null){
            return "login";
        }

        //如果已登录但未实名
        if(user.getRealstatus()!=3){
            return "user";
        }
        return "new_back";
    }

    //点击提交项目的按钮   将对应的草稿提交状态 从0变成1
    @RequestMapping("/publishProject")
    @ResponseBody //以json字符串的形式返回
    public String publishProject(HttpSession session){
        Project project=(Project)session.getAttribute("projectTemp");


        if(project==null){
            return "fail";
        }


        boolean flag=(!(project.getPtitle().trim().equals("")))&&(!(project.getPstory().trim().equals("")));
        if((project.getPtitle()!=null)&&(project.getPstory()!=null)&&flag==true){
            //将临时项目状态从 0 变成  1
            int i = pps.publishProject(project);
            if(i>0){
                session.setAttribute("projectTemp",null);
                List<Back> backList = new ArrayList<>();
                session.setAttribute("backList",backList);
                return "success";
            }
        }

        return "fail";

    }

    //删除回报
    @RequestMapping("/deleteBack")
    public String deleteBack(Back back,HttpSession session){
        int i = pps.deleteBack(back);
        Integer pno=((Project)session.getAttribute("projectTemp")).getPno();
        List<Back> backList = pps.getBacksByPno(pno);
        session.setAttribute("backList",backList);

        return "new_back";
    }

    //添加回报
    @RequestMapping("/addBack")
    public String addBack(Back back,HttpSession session){
        System.out.println(back);
        Integer pno=((Project)session.getAttribute("projectTemp")).getPno();
        back.setPno(pno);
        int i = pps.addBack(back);
        List<Back> backList = pps.getBacksByPno(pno);
        session.setAttribute("backList",backList);

        return "new_back";
    }

}
